//
//  FKGoodsFilterView.m
//  WanTao
//
//  Created by Macbook Pro on 2019/3/19.
//  Copyright © 2019 Macbook Pro. All rights reserved.
//

#import "FKGoodsFilterView.h"
#import "FKCustomBtn.h"
#import "FKGoodsFilterCell.h"

@interface FKGoodsFilterView ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, weak) FKCustomBtn *categoryBtn;
@property (nonatomic, weak) FKCustomBtn *ageBtn;
@property (nonatomic, weak) FKCustomBtn *priceBtn;
@property (nonatomic, weak) FKCustomBtn *salesBtn;

@property (nonatomic, weak) UITableView *categoryTable;
@property (nonatomic, strong) NSArray *categories;

@property (nonatomic, weak) UITableView *subCategoryTable;
@property (nonatomic, strong) NSArray *subCategories;

@property (nonatomic, weak) UITableView *agesTable;
@property (nonatomic, strong) NSArray *ages;

@property (nonatomic, strong) UIView *cover;

/** 是否是按价格升序排序 */
@property (nonatomic, assign, getter=isPriceAsc) BOOL priceAsc;
/** 是否是按销量升序排序 */
@property (nonatomic, assign, getter=isSalesAsc) BOOL salesAsc;

@property (nonatomic, strong) NSMutableDictionary *param;

@end

@implementation FKGoodsFilterView

- (void)setCateList:(NSArray *)cateList
{
    _cateList = cateList;
    
    self.categories = cateList;
    [self.categoryTable reloadData];
    
    [self updateSelectedCate];
}

- (void)updateSelectedCate
{
    // 判断是不是从首页点击进来的
    NSDictionary *cateItem = [FKCacheTool cateItem];
    if (cateItem) {
        for (NSDictionary *cate in self.cateList) {
            if ([cate[@"id"] isEqualToString:cateItem[@"id"]]) {
                NSInteger index = [self.cateList indexOfObject:cate];
                NSIndexPath *indexPath = [NSIndexPath indexPathForRow:index inSection:0];
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.categoryTable selectRowAtIndexPath:indexPath animated:true scrollPosition:UITableViewScrollPositionNone];
                    [self tableView:self.categoryTable didSelectRowAtIndexPath:indexPath];
                });
//                [FKCacheTool saveCateItem:nil];
                break;
            }
        }
    }
}

- (void)setAgeRange:(NSArray *)ageRange
{
    _ageRange = ageRange;
    
    self.ages = ageRange;
    [self.agesTable reloadData];
}

- (NSArray *)categories
{
    if (!_categories) {
        _categories = [NSArray array];
    }
    return _categories;
}

- (NSArray *)subCategories
{
    if (!_subCategories) {
        _subCategories = [NSArray array];
    }
    return _subCategories;
}

- (NSMutableDictionary *)param
{
    if (!_param) {
        _param = [NSMutableDictionary dictionary];
    }
    return _param;
}

- (NSArray *)ages
{
    if (!_ages) {
        _ages = [NSArray array];
    }
    return _ages;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        [self setupSubviews];
    }
    return self;
}

- (void)setupSubviews
{
    
    UIView *container = [[UIView alloc] initWithFrame:CGRectMake(0, 0, fkScreenW, fk_adjustW(45))];
    [self addSubview:container];
    container.backgroundColor = [UIColor whiteColor];
    
    NSArray *titles = @[@"商品分类", @"年龄", @"价格", @"销量"];
    CGFloat margin = 12;
    CGFloat itemH = container.fk_height;
    CGFloat itemW = (fkScreenW - 24) / titles.count;
    for (NSInteger index = 0; index < titles.count; index++) {
        FKCustomBtn *itemBtn = [FKCustomBtn fk_btnWithTarget:self action:@selector(itemBtnClicked:) font:fk_adjustFont(14) normalTitle:titles[index] normalTitleColor:fkColor666666 selectedTitle:nil selectedTitleColor:fkMainColor normalImg:[UIImage imageNamed:@"triangle"] selectedImg:nil bgImg:nil selectedBgImg:nil];
        [container addSubview:itemBtn];
        itemBtn.imagePosition = FKImagePositionRight;
        itemBtn.tag = 10 + index;
        if (index == 0) {
            itemBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        } else if (index == titles.count - 1) {
            itemBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
        }
        if (index < 2) {
            [itemBtn setImage:[UIImage imageNamed:@"triangle_up"] forState:UIControlStateSelected];
        }
        
        CGFloat itemX = margin + index * itemW;
        itemBtn.frame = CGRectMake(itemX, 0, itemW, itemH);
    }
    self.categoryBtn = [container viewWithTag:10];
    self.ageBtn = [container viewWithTag:11];
    self.priceBtn = [container viewWithTag:12];
    self.salesBtn = [container viewWithTag:13];
    
    CGFloat categoryTableW = fkScreenW * 0.5;
//    CGFloat tableH = fk_adjustW(185);
    UITableView *categoryTable = [[UITableView alloc] initWithFrame:CGRectMake(0, container.fk_bottom, categoryTableW, 0) style:UITableViewStylePlain];
    [self addSubview:categoryTable];
    self.categoryTable = categoryTable;
    categoryTable.dataSource = self;
    categoryTable.delegate = self;
    categoryTable.separatorStyle = UITableViewCellSeparatorStyleNone;
    categoryTable.showsVerticalScrollIndicator = false;
    
    UITableView *subCategoryTable = [[UITableView alloc] initWithFrame:CGRectMake(categoryTable.fk_right, container.fk_bottom, categoryTableW, 0) style:UITableViewStylePlain];
    [self addSubview:subCategoryTable];
    self.subCategoryTable = subCategoryTable;
    subCategoryTable.dataSource = self;
    subCategoryTable.delegate = self;
    subCategoryTable.separatorStyle = UITableViewCellSeparatorStyleNone;
    subCategoryTable.showsVerticalScrollIndicator = false;
    
    UITableView *agesTable = [[UITableView alloc] initWithFrame:CGRectMake(0, container.fk_bottom, fkScreenW, 0) style:UITableViewStylePlain];
    [self addSubview:agesTable];
    self.agesTable = agesTable;
    agesTable.dataSource = self;
    agesTable.delegate = self;
    agesTable.separatorStyle = UITableViewCellSeparatorStyleNone;
    agesTable.showsVerticalScrollIndicator = false;
    
    UIView *cover = [[UIView alloc] initWithFrame:CGRectMake(0, container.fk_bottom, fkScreenW, 0)];
    cover.backgroundColor = fkColorAlpha(0, 0, 0, 0.5);
    self.cover = cover;
    cover.hidden = true;
    [cover addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(fold)]];
    
    UIView *separator = [[UIView alloc] initWithFrame:CGRectMake(0, fk_adjustW(45) - 0.8, fkScreenW, 0.8)];
    [self addSubview:separator];
    separator.backgroundColor = [UIColor groupTableViewBackgroundColor];
}

- (void)itemBtnClicked:(FKCustomBtn *)btn
{
    if ([btn isEqual:self.categoryBtn]) {
        btn.selected = !btn.isSelected;
        self.ageBtn.selected = false;
        btn.isSelected ? [self showCateTable] : [self fold];
    } else if ([btn isEqual:self.ageBtn]) {
        btn.selected = !btn.isSelected;
        self.categoryBtn.selected = false;
        btn.isSelected ? [self showAgeTable] : [self fold];
        
    } else if ([btn isEqual:self.priceBtn]) {
        [self fold];
        btn.selected = true;
        self.salesBtn.selected = false;
        
        self.priceAsc = !self.isPriceAsc;
        self.param[@"price"] = self.isPriceAsc ? @"2" : @"1";
        self.param[@"sales"] = @"";
        [btn setImage:[UIImage imageNamed:self.priceAsc ? @"triangle_up" : @"triangle_down"] forState:UIControlStateSelected];
        if (self.updateFilterBlock) self.updateFilterBlock(self.param);
    } else if ([btn isEqual:self.salesBtn]) { // 销量和价格之间的筛选是互斥的
        [self fold];
        btn.selected = true;
        self.priceBtn.selected = false;
        
        self.salesAsc = !self.isSalesAsc;
        self.param[@"sales"] = self.isSalesAsc ? @"2" : @"1";
        self.param[@"price"] = @"";
        [btn setImage:[UIImage imageNamed:self.salesAsc ? @"triangle_up" : @"triangle_down"] forState:UIControlStateSelected];
        if (self.updateFilterBlock) self.updateFilterBlock(self.param);
    }
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if ([tableView isEqual:self.categoryTable]) {
        return self.categories.count;
    } else if ([tableView isEqual:self.subCategoryTable]) {
        return self.subCategories.count;
    } else {
        return self.ages.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    FKGoodsFilterCell *cell = [FKGoodsFilterCell cellWith:tableView];
    if ([tableView isEqual:self.categoryTable]) {
        cell.data = self.categories[indexPath.row];
    } else if ([tableView isEqual:self.subCategoryTable]) {
        cell.data = self.subCategories[indexPath.row];
        cell.canShowIcon = true;
    } else {
        cell.data = self.ages[indexPath.row];
        cell.canShowIcon = true;
    }
    return cell;
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return fk_adjustW(44);
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([tableView isEqual:self.categoryTable]) {
        NSDictionary *category = self.categories[indexPath.row];
        self.subCategories = category[@"item_cate"];
        if (self.subCategories.count == 0) {
            [self.categoryBtn setTitle:category[@"name"] forState:UIControlStateNormal];
            [self fold];
            // 更新请求参数
            self.param[@"cate_id"] = category[@"id"];
            if (self.updateFilterBlock) self.updateFilterBlock(self.param);
        } else {
            // 判断是不是从首页点击进来的
            if ([FKCacheTool cateItem]) {
                [self.categoryBtn setTitle:category[@"name"] forState:UIControlStateNormal];
                self.param[@"cate_id"] = category[@"id"];
                if (self.updateFilterBlock) self.updateFilterBlock(self.param);
                [FKCacheTool saveCateItem:nil];
            }
        }
        [self.subCategoryTable reloadData];
    } else if ([tableView isEqual:self.subCategoryTable]) {
        NSDictionary *subCategory = self.subCategories[indexPath.row];
        [self.categoryBtn setTitle:subCategory[@"name"] forState:UIControlStateNormal];
        [self fold];
        // 更新请求参数
        self.param[@"cate_id"] = subCategory[@"id"];
        if (self.updateFilterBlock) self.updateFilterBlock(self.param);
    } else {
        NSDictionary *ageRange = self.ages[indexPath.row];
        [self.ageBtn setTitle:ageRange[@"name"] forState:UIControlStateNormal];
        [self fold];
        // 更新请求参数
//        self.param[@"age"] = ageRange[@"id"];
        if (self.updateFilterBlock) self.updateFilterBlock(self.param);
    }
}


- (void)showCateTable
{
    if (!self.cateList) {
        [SVProgressHUD showInfoWithStatus:@"数据加载中，请稍后再试"];
        return;
    }
    
    [UIView animateWithDuration:0.25 animations:^{
        CGFloat tableH = fk_adjustW(185);
        self.categoryTable.fk_height = tableH;
        self.subCategoryTable.fk_height = tableH;
        self.fk_height = fk_adjustW(45) + tableH;
    } completion:^(BOOL finished) {
        self.agesTable.fk_height = 0;
        self.ageBtn.selected = false;
        
        UIWindow *window = [UIApplication sharedApplication].delegate.window;
        self.cover.hidden = false;
        CGRect coverF = [self fk_convertRect:CGRectMake(0, self.categoryTable.fk_bottom, fkScreenW, fkScreenH) toViewOrWindow:window];
        self.cover.frame = coverF;
        [window addSubview:self.cover];
    }];
}

- (void)showAgeTable
{
    if (!self.ageRange) {
        [SVProgressHUD showInfoWithStatus:@"数据加载中，请稍后再试"];
        return;
    }
    
    [UIView animateWithDuration:0.25 animations:^{
        CGFloat tableH = fk_adjustW(185);
        self.agesTable.fk_height = tableH;
        self.fk_height = fk_adjustW(45) + tableH;
    } completion:^(BOOL finished) {
        self.categoryTable.fk_height = 0;
        self.subCategoryTable.fk_height = 0;
        self.categoryBtn.selected = false;
        
        UIWindow *window = [UIApplication sharedApplication].delegate.window;
        self.cover.hidden = false;
        CGRect coverF = [self fk_convertRect:CGRectMake(0, self.agesTable.fk_bottom, fkScreenW, fkScreenH) toViewOrWindow:window];
        self.cover.frame = coverF;
        [window addSubview:self.cover];
    }];
}

- (void)fold
{
    [UIView animateWithDuration:0.25 animations:^{
        self.agesTable.fk_height = 0;
        self.categoryTable.fk_height = 0;
        self.subCategoryTable.fk_height = 0;
        self.fk_height = fk_adjustW(45);
        self.cover.hidden = true;
        
        self.categoryBtn.selected = false;
        self.ageBtn.selected = false;
    }];
}

@end
